package com.security.service;

import com.entity.ConditionType;
import com.entity.User;
import com.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

@Service
// 给该类下面所有使用到缓存注解的方法，统一配置属性
@CacheConfig(
        cacheManager = "customCacheManager"
)
public class CacheService {
    @Autowired
    UserRepository userRepository;

    @Cacheable(
            value = {"user", "info"}, // 多个cacheNames时，每个名字会缓存一份数据
            key = "'all'",
            condition = "#type.needCache()",
            unless = "#result==null"
    )
    public List<User> searchAll(ConditionType type) {
        return userRepository.findAll();
    }

    @Transactional
    @CacheEvict(
            cacheNames = {"user", "info"},
            key = "'all'",
            beforeInvocation = true
    )
    public void add() {
        User user = new User("1001", "admin", "123456");
        userRepository.save(user);
    }

    @Transactional
    @CachePut(
            cacheNames = {"info"},
            key = "'all'"
    )
    public User update() {
        User originUser = userRepository.findByUsername("admin");
        Objects.requireNonNull(originUser);
        originUser.setUsername("update user");
        originUser.setPassword("654321");
        return userRepository.save(originUser);
    }

    @Transactional
    @CacheEvict(
            cacheNames = {"user"},
            key = "'all'",
            beforeInvocation = true
    )
    public void deleteAll() {
        userRepository.deleteAll();
    }
}
